/**
 * 数据库配置
 */
const mysql = require("mysql2");
const config = {
  host: "localhost",
  port: "3306",
  user: "root",
  password: "123456",
  database: "peak-todo",
  connectTimeout: 5000,
  // timezone: "+08:00",
  dateStrings: true, // 默认false将被解析为Date对象格式2023-11-27T03:39:09.164Z
};

const pool = mysql.createPool(config);
const poolPromise = pool.promise();

/**
 * 新建查询连接
 * @param {*} sql
 * @returns
 */
function querySql(sql) {
  return new Promise((resolve, reject) => {
    try {
      pool.query(sql, (err, result) => {
        if (err) {
          reject(err);
        } else {
          resolve(result);
        }
      });
    } catch (e) {
      reject(e);
    }
  });
}

// 查询一条语句
function queryOne(sql) {
  return new Promise((resolve, reject) => {
    querySql(sql)
      .then((res) => {
        console.log("res===", res);
        if (res && res.length > 0) {
          resolve(res[0]);
        } else {
          resolve(null);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

module.exports = {
  pool,
  poolPromise,
};
